from django_redis import get_redis_connection
from rest_framework import  serializers

from fjr.models import SKU


class UserBrowseSerializer(serializers.Serializer):

    sku_id = serializers.IntegerField(required=False)

    def validate_sku_id(self, value):
        try:
            sku_id = SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('sku不存在')

        return value

    def create(self, validated_data):
        # 保存用户浏览数据
        user = self.initial_data['user']
        redis_conn = get_redis_connection('history')
        pl = redis_conn.pipeline()

        # 先去重
        pl.lrem('history_%s' % user.id, 0, validated_data['sku_id'])
        # 在储存
        pl.lpush('history_%s' % user.id, validated_data['sku_id'])
        # 最后截取
        pl.ltrim('history_%s' % user.id, 0, 4)
        # 执行管道
        pl.execute()

        return validated_data


class UserBrowseListSerializer(serializers.ModelSerializer):

    class Meta:
        model = SKU
        fields = ('id', 'name', 'price', 'comments', 'default_image')
